package com.sysd.mail.util;

/**
 * @author Jeff Schnitzer
 */
public class EmailUtils {
    /**
     * @return true if the string is a valid email address
     */
//    public static boolean isValidEmailAddress(String address) {
//        // MAIL FROM: <>
//        if (address.length() == 0) {
//            return true;
//        }
//        InternetAddress[] ia = new InternetAddress[0];
//        try {
//            ia = InternetAddress.parse(address, true);
//        } catch (AddressException e) {
//            e.printStackTrace();
//        }
//        return ia.length != 0;
//    }

    /**
     * Extracts the email address within a <> after a specified offset.
     */
    public static String extractEmailAddress(String args, int offset) {
        String address = args.substring(offset).trim();
        if (address.indexOf('<') == 0) {
            address = address.substring(1, address.indexOf('>'));
            // spaces within the <> are also possible, Postfix apparently
            // trims these away:
            return address.trim();
        }

        // find space (e.g. SIZE argument)
        int nextarg = address.indexOf(" ");
        if (nextarg > -1) {
            address = address.substring(0, nextarg).trim();
        }
        return address;
    }

    /**
     * Normalize the domain-part to lowercase.  If email address is missing
     * an '@' the email is returned as-is.
     */
    public static String normalizeEmail(String email) {
        int atIndex = email.indexOf('@');
        System.out.println(atIndex);
        if (atIndex < 0) {
            return email;
        } else {
            return email.substring(0, atIndex) + email.substring(atIndex).toLowerCase();
        }
    }

    /**
     * 获取邮件地址后面的域名
     *
     * @param email 邮件地址
     * @return 域名
     */
    public static String getDomain(String email) {
        int index = email.indexOf("@");
        if (index < 0) {
            return email;
        }
        return email.substring(index + 1).toLowerCase();
    }

}
